from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll

# Index of Poll
def index(request):
    polls = Poll.objects.all().order_by("-created_at")[:5]
    return render_to_response("polls/index.html", {"polls": polls})

# Displays form for voting
def details(request, id):
    p = get_object_or_404(Poll, pk = id)
    return render_to_response("polls/details.html", {"poll": p}, context_instance=RequestContext(request))

# Displays results of poll
def results(request, id):
    p = get_object_or_404(Poll, pk = id)
    return render_to_response("polls/results.html", {"poll": p})


# Counts user voting
def vote(request, id):
    p = get_object_or_404(Poll, pk = id)
    try:
        selected_choice = p.choice_set.get(pk = request.POST["choice"])
    except (KeyError, Choice.DoesNotExist):
        return render_to_response("polls/details.html", {"poll": p})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse("poll_results", args=(p.id,)))


# Secured view
@login_required
def secured(request):
    return render_to_response("polls/secured.html")